const Webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const path = require('path')

const os = require('os')
const portfinder = require('portfinder')
const ora = require('ora')

const utils = require('./util')
const chalk = require('chalk')

const dotenv = require('dotenv')
const DotenvWebpack = require('dotenv-webpack')




const calcConfig = utils.calcPath()
if (calcConfig === false) return false
const dev = process.env.NODE_ENV === 'development' //判断是否在运行环境
let webpackConfig = require(dev ? './webpack.dev.js' : './webpack.prod.js')(
  calcConfig
),
  webpackPrdConfig = null
if (!dev) webpackPrdConfig = require('./webpack.prod.js')(calcConfig, true)

/**
 * @description: 项目运行的环境变量配置
 * @return {*}
 */
const envConfigPath = {
  development: path.resolve(__dirname, './env/.env.development'), // 开发环境配置
  gray: path.resolve(__dirname, './env/.env.gray'), // 预发布环境配置
  production: path.resolve(__dirname, './env/.env.production'), // 正式环境配置
}
const currentName = process.argv[process.argv.length - 2]
const envConfig = dotenv.config({
  path: path.resolve(__dirname, envConfigPath[currentName]), // 配置文件路径
  encoding: 'utf8', // 编码方式，默认utf8
  debug: false, // 是否开启debug，默认false
}).parsed
if (!envConfig) {
  console.log('配置文件不存在-退出程序', envConfig)
  process.exit(1)
}
webpackConfig.plugins.unshift(
  new DotenvWebpack({
    path: envConfigPath[currentName], // 配置文件路径
  })
)
/**
 * @description: 是否在打包环境中使用代码混淆
 * @return {*}
 */
if (envConfig.VUE_APP_TOCONFUSE === 'true' && !dev) {

  const JavaScriptObfuscator = require('webpack-obfuscator');//代码混淆插件
  /**
   * @description: 配置地址：https://www.qiushaocloud.top/2022/07/05/zhuan-zai-vue-webpack-obfuscator.html
   */
  const obfuscatorConfig = require('./obfuscator.config.js');//配置文件
  webpackConfig.plugins.unshift(//低混淆
    new JavaScriptObfuscator(obfuscatorConfig.config, [])
  )
}
/* 项目运行的环境变量配置end */

let networkInterfaceInfo = os.networkInterfaces(),
  ipAddress = ''

for (let interfaceName in networkInterfaceInfo) {
  let interfaceInfos = networkInterfaceInfo[interfaceName]
  for (let interfaceInfo of interfaceInfos) {
    if (
      /ipv4/i.test(interfaceInfo.family) &&
      interfaceInfo.address !== '127.0.0.1' &&
      !interfaceInfo.internal
    ) {
      ipAddress = interfaceInfo.address
      break
    }
  }
}

if (dev) {
  const moduleConfig = require(path.join(calcConfig.modulePath, 'config.js'))
  const type = moduleConfig.type

  portfinder.getPort((error, port) => {
    const host = '0.0.0.0'
    //port = 80;
    const devServerConfig = {
      stats: 'errors-only',
      host,
      port,
      hot: true,
      inline: true,
      progress: true,
      contentBase: [
        path.join(calcConfig.basePath, 'dll/vue_dll_dev'),
        path.join(calcConfig.basePath, 'dll/react_dll_dev'),
      ],
      historyApiFallback: true,
      disableHostCheck: true,
      clientLogLevel: 'none',
      // historyApiFallback: {
      //     verbose: true,
      //     rewrites: [
      //         {from: new RegExp(calcConfig.moduleName + '\/*', 'ig'), to: path.posix.join('/', 'index.html')}
      //     ]
      // }
    }

    webpackConfig.plugins.unshift(
      new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [
            chalk.yellow(
              `Project is running at \n
                            http://localhost:${port}/${type === 'vue'
                ? `hxswap/${calcConfig.moduleName}`
                : calcConfig.moduleName
              }
                            http://${ipAddress}:${port}/${type === 'vue'
                ? `hxswap/${calcConfig.moduleName}`
                : calcConfig.moduleName
              }
                    `
            ),
          ],
        },
        clearConsole: true,
      })
    )

    const devServer = new WebpackDevServer(
      Webpack(webpackConfig),
      devServerConfig
    )

    devServer.listen(port, host, (error) => {
      if (error) console.info(chalk.red(error))
    })
  })
} else if (process.env.NODE_ENV === 'production') {
  const spinner = ora('building for production...')
  spinner.start()

  Webpack(
    webpackPrdConfig ? [webpackConfig, webpackPrdConfig] : webpackConfig
  ).run((err, stats) => {
    spinner.stop()
    if (err) throw err

    process.stdout.write(
      stats.toString({
        colors: true,
        modules: false,
        children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
        chunks: false,
        chunkModules: false,
      }) + '\n\n'
    )

    console.log(chalk.cyan(`  Build ${calcConfig.moduleName} complete.\n`))
  })
}
